package cn.vc.gateway.filter;

import cn.vc.basicmodule.entity.Result;
import cn.vc.gateway.util.IPUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jdk.internal.dynalink.linker.LinkerServices;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.util.IPAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
//import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

@Slf4j
@Order(1)
@Component
@ConfigurationProperties(prefix = "wallet")
public class AuthorizeFilter implements GlobalFilter {
//    @Autowired
//    private StringRedisTemplate stringRedisTemplate;

    @Value("trust-ip")
    private List<String> trustIp;
    public void setTrustIp(List<String> trustIp) {
        this.trustIp = trustIp;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 获取请求方式
        String method = request.getMethod().name();
        // 获取请求路径
        String path = request.getPath().value();
        // 获取IP地址
        String ip = IPUtils.getIpAddress(request);
        System.out.println(path);
        // 请求路径为 扣除钻石 的 高危险请求，外部不允许请求
        if (path.equals("/wallet/wallet/deduction")) {
            for (String i : trustIp) {
                if (ip.equals(i)) {
                    return chain.filter(exchange);
                }
            }
            // 返回错误信息
            byte[] bits = JSON.toJSONString(new Result<>(0, null, "未经允许的请求！！！")).getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = response.bufferFactory().wrap(bits);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //指定编码，否则在浏览器中会中文乱码
            response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
            return response.writeWith(Mono.just(buffer));
        }

        return chain.filter(exchange);
//
//        System.out.println("======");
//        log.info("请求：{}", path);
//
//        // 为GET方法
//        if ("GET".equals(method)) {
//            log.info("GET请求放行");
//            // 放行
//            return chain.filter(exchange);
//        } else if ("POST".equals(method)) {
//            log.info("POST请求放行");
//            // 放行
//            return chain.filter(exchange);
//        }
//
//        // 如果包含"/"则按照"/"分割并获取第一个"/"后的路径，如果不包含则返回null
//        String[] paths = path.split("/");
//        String firstPath = paths.length>1 ? paths[1] : null;
//        System.out.println("路径："+firstPath);
//        // 为null说明请求无效
//        if (firstPath==null||"index.js".equals(firstPath)||"PC".equals(firstPath)||"res_js".equals(firstPath)||"img".equals(firstPath)) {
//            return chain.filter(exchange);
//        }
//        if ("userstatic".equals(firstPath)||"videostatic".equals(firstPath)) {
//            log.info("静态资源：放行");
//            return chain.filter(exchange);
//        }
////        if (firstPath==null|| firstPath.isEmpty()) {
////            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
////            return exchange.getResponse().setComplete();
////        }
//        // 如果为指定路径的请求则直接放行
//        if (firstPath.equals("login") || firstPath.equals("captcha")) {
//            log.info("为login或captcha的请求，直接放行。");
//            return chain.filter(exchange);
//        }
//        // 获取请求头
//        HttpHeaders httpHeaders = request.getHeaders();
//        // 获取key为token的value
//        String token = httpHeaders.getFirst("token");
//        // 为空说明未登录
//        if (token == null) {
//            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
//            return exchange.getResponse().setComplete();
//        }
//        // 获取登录用户信息
//        String userJSON = stringRedisTemplate.opsForValue().get(token);
//        System.out.println(userJSON);
//        if (userJSON == null) {
//            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
//            return exchange.getResponse().setComplete();
//        }
////        User myUser = JSON.parseObject(userJSON, User.class);
////        System.out.println("用户 -> "+myUser);
////        // 登录信息为空
////        if (myUser == null) {
////            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
////            return exchange.getResponse().setComplete();
////        }
////        // feign远程查询用户信息，判断用户是否存在并且相同
////        Result<User> result = userClient.selectUser(myUser.getAccount(), myUser.getPassword());
////        if (result.getCode() == 0 || !(myUser.getAccount().equals(result.getData().getAccount()) && myUser.getPassword().equals(result.getData().getPassword()))) {
////            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
////            return exchange.getResponse().setComplete();
////        }
//        log.info("已登录: 放行");
//        return chain.filter(exchange);
    }
}
